import ajax from './ajax'
import { LocalStorage } from 'quasar'

const _loadAccount = () => {
  return LocalStorage.get.item('account');
};

const _initAccount = (account) => {
  LocalStorage.set('account', account);
}

const _hasRole = (role) => {
  let account = _loadAccount();
  if(account) {
    let roles = LocalStorage.get.item('account').roles;
    if(roles) {
      return roles.join(',').indexOf(role) >= 0;
    }
  }
  return false;
};

const _hasMenu = (menuId) => {
  let account = _loadAccount();
  if(account) {
    let roles = LocalStorage.get.item('account').roles;
    if(roles && roles.length > 0) {
      for(let i = 0; i < roles.length; i++) {
        let role = roles[i];
        if(role.indexOf("MENU") >= 0) {
          let marks = parseInt(role.substring(4));
          return (marks & Math.pow(2, menuId)) > 0;
        }
      }
    }
  }
  return true;
};

export default {
  login(code, password, onSuccess) {
    let account = _loadAccount();
    let openId = '';
    if(account && account.openId) {
      openId = account.openId;
    }
    ajax.post('/login', {code:code, password:password, openId:openId})
        .then(function(res){
          let data = res.data;
          _initAccount(data.model);
          if(onSuccess) {
            onSuccess(res);
          }
          // location.reload();
        });  
  },

  initAccount(account) {
    _initAccount(account);
  },

  hasToken() {
    let account = _loadAccount();
    return (account && account.token) ? true : false;
  },

  hasMenu(menuId) {
    // 有角色 MENUxxx 才进行拦截
    return _hasMenu(menuId);
  },

  isAdmin() {
    return _hasRole('ADMIN');
  },

  isAuthor() {
    return _hasRole('AUTHOR');
  },

  isDouyinMcn() {
    return _hasRole('DOUYIN_MCN')
  },

  localAccount() {
    return _loadAccount();
  },

  loadAccounts(onSuccess) {
    ajax.get('/accounts').then(onSuccess);  
  },

  createAccount(account, onSuccess) {
    ajax.post('/accounts', {
      code: account.code,
      password: account.password,
      userName: account.name,
      role: account.role
    })
    .then(onSuccess)
    .catch(err=>{console.log(err)});
  },

  changePassword(password, password1, onSuccess) {
    ajax.post('/accounts/password', {password:password,password1:password1})
        .then(onSuccess); 
  },

  changeEmailFlag(flag, onSuccess) {
    let account = _loadAccount();
    account.flag = flag ? 1 : 0;
    _initAccount(account);

    ajax.post('/accounts/email/flag?flag=' + account.flag)
        .then(onSuccess); 
  }
};